package com.qin.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qin.mall.dao.*;
import com.qin.mall.domain.*;
import com.qin.mall.dto.PmsProductParam;
import com.qin.mall.dto.PmsProductQueryParam;
import com.qin.mall.mapper.*;
import com.qin.mall.service.PmsProductService;


import com.qin.mall.dto.PmsProductResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 覃剑
* @description 针对表【pms_product(商品信息)】的数据库操作Service实现
* @createDate 2022-11-07 11:19:33
*/
@Service
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct>
    implements PmsProductService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);


    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsMemberPriceDao memberPriceDao;
    @Autowired
    private PmsProductLadderDao productLadderDao;
    @Autowired
    private PmsProductFullReductionDao productFullReductionDao;
    @Autowired
    private PmsSkuStockDao skuStockDao;
    @Autowired
    private PmsProductAttributeValueDao productAttributeValueDao;
    @Autowired
    private CmsSubjectProductRelationDao subjectProductRelationDao;
    @Autowired
    private CmsPrefrenceAreaProductRelationDao prefrenceAreaProductRelationDao;
    @Autowired
    private PmsProductDao productDao;
    @Autowired
    private PmsMemberPriceMapper memberPriceMapper;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private CmsSubjectProductRelationMapper subjectProductRelationMapper;
    @Autowired
    private CmsPrefrenceAreaProductRelationMapper prefrenceAreaProductRelationMapper;
    @Autowired
    private PmsProductVertifyRecordDao productVertifyRecordDao;
    @Autowired
    private PmsProductVertifyRecordMapper productVertifyRecordMapper;

    /**
     * 创建商品
     * @param productParam
     * @return
     */
    @Override
    public int create(PmsProductParam productParam) {
        int count;
        //创建商品
        PmsProduct product = productParam;
        product.setId(null);
        int insert = productMapper.insert(productParam);
        //根据促销类型设置价格：、阶梯价格、满减价格
        Long productId = product.getId();
        //会员价格
        relateAndInsertList(memberPriceDao,productParam.getMemberPriceList(),productId);
        //阶梯价格
        relateAndInsertList(productLadderDao,productParam.getProductLadderList(),productId);
        //满减价格
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(),productId);
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId);
        //添加sku库存信息
        relateAndInsertList(skuStockDao, productParam.getSkuStockList(), productId);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), productId);
        //关联专题
        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), productId);
        //关联优选
        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), productId);
        count = 1;
        return count;
    }

    //处理库存编码
    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if(CollectionUtils.isEmpty(skuStockList))return;
        for(int i=0;i<skuStockList.size();i++){
            PmsSkuStock skuStock = skuStockList.get(i);
            if(StringUtils.isEmpty(skuStock.getSkuCode())){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i+1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }


    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}",e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public PmsProduct select(Long id) {
        PmsProduct product = productMapper.selectById(id);
        return product;
    }

    /**
     * 根据商品编号获取更新前的信息,和其他关联的所有的信息
     * @param id
     * @return
     */
    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        PmsProductResult result = productDao.getUpdateInfo(id);
        return result;
    }

    /**
     * 更新商品
     * @param id
     * @param productParam
     * @return
     */
    @Override
    public int update(Long id, PmsProductParam productParam) {
        int count;
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        // 不能使用子类进行条件构造
        // 1.使用父类，后果->就是会导致，子类属性无法构造成功 这个
        // 使用对应方法更改 子类的属性
        int update = productMapper.update(productParam, wrapper);
        //会员价格
             // 原本是先删除 再使用建立关系表的方法
        QueryWrapper<PmsMemberPrice> priceQueryWrapper = new QueryWrapper<>();
            // 原本的Exapmel 相当于条件构造器
        priceQueryWrapper.eq("product_id",id);
        int delete1 = memberPriceMapper.delete(priceQueryWrapper);
            //重新建立 关系表
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id);
        
        //阶梯价格
        QueryWrapper<PmsProductLadder> ladderQueryWrapper = new QueryWrapper<>();
        ladderQueryWrapper.eq("product_id",id);
        int delete2 = productLadderMapper.delete(ladderQueryWrapper);
        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), id);
        
        // 满减价格
        QueryWrapper<PmsProductFullReduction> fullReductionQueryWrapper = new QueryWrapper<>();
        fullReductionQueryWrapper.eq("product_id",id);
        int delete3 = productFullReductionMapper.delete(fullReductionQueryWrapper);
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id);

        //修改sku库存信息
        handleUpdateSkuStockList(id, productParam);

        
        //修改商品参数,添加自定义商品规格
        QueryWrapper<PmsProductAttributeValue> attributeValueQueryWrapper = new QueryWrapper<>();
        attributeValueQueryWrapper.eq("product_id",id);
        int delete = productAttributeValueMapper.delete(attributeValueQueryWrapper);
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), id);

        //关联专题
        QueryWrapper<CmsSubjectProductRelation> subjectProductRelationQueryWrapper = new QueryWrapper<>();
        subjectProductRelationQueryWrapper.eq("product_id",id);
        int delete4 = subjectProductRelationMapper.delete(subjectProductRelationQueryWrapper);
        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), id);

        //关联优选
        QueryWrapper<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelationQueryWrapper = new QueryWrapper<>();
        prefrenceAreaProductRelationQueryWrapper.eq("product_id",id);
        int delete5 = prefrenceAreaProductRelationMapper.delete(prefrenceAreaProductRelationQueryWrapper);
        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), id);
        count = 1;
        return count;
    }

    private void handleUpdateSkuStockList(Long id, PmsProductParam productParam) {
        //当前的sku信息
        List<PmsSkuStock> currSkuList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if(CollUtil.isEmpty(currSkuList)){
            QueryWrapper<PmsSkuStock> skuStockQueryWrapper = new QueryWrapper<>();
            skuStockQueryWrapper.eq("product_id",id);
            int delete = skuStockMapper.delete(skuStockQueryWrapper);
            return;
        }
        //获取初始sku信息
        QueryWrapper<PmsSkuStock> skuStockQueryWrapper = new QueryWrapper<>();
        skuStockQueryWrapper.eq("product_id",id);
        List<PmsSkuStock> oriStuList = skuStockMapper.selectList(skuStockQueryWrapper);
        //获取新增sku信息
        List<PmsSkuStock> insertSkuList = currSkuList.stream().filter(item->item.getId()==null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<PmsSkuStock> updateSkuList = currSkuList.stream().filter(item->item.getId()!=null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        //获取需要删除的sku信息
        List<PmsSkuStock> removeSkuList = oriStuList.stream().filter(item-> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        handleSkuStockCode(insertSkuList,id);
        handleSkuStockCode(updateSkuList,id);
        //新增sku
        if(CollUtil.isNotEmpty(insertSkuList)){
            relateAndInsertList(skuStockDao, insertSkuList, id);
        }
        //删除sku
        if(CollUtil.isNotEmpty(removeSkuList)){
            List<Long> removeSkuIds = removeSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            QueryWrapper<PmsSkuStock> removeQueryWrapper = new QueryWrapper<>();
            removeQueryWrapper.in("id",removeSkuIds);
            int delete = skuStockMapper.delete(removeQueryWrapper);
        }
        //修改sku
        if(CollUtil.isNotEmpty(updateSkuList)){
            for (PmsSkuStock pmsSkuStock : updateSkuList) {
                int update = skuStockMapper.updateById(pmsSkuStock);
            }
        }

    }

    /**
     * 分页查询商品
     * @param productQueryParam
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<PmsProduct> getList(PmsProductQueryParam productQueryParam, Integer pageNum, Integer pageSize) {
        Page<PmsProduct> page = new Page<>(pageNum, pageSize);
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        if (productQueryParam.getPublishStatus() != null) {
            wrapper.eq("publish_status",productQueryParam.getPublishStatus());
        }
        if (productQueryParam.getVerifyStatus() != null) {
           wrapper.eq("verify_status",productQueryParam.getVerifyStatus());
        }
        if (productQueryParam.getKeyword() != null) {
            wrapper.like("name","%"+productQueryParam.getKeyword()+"%");
        }
        if (productQueryParam.getProductSn() != null) {
            wrapper.eq("prodct_sn",productQueryParam.getProductSn());
        }
        if (productQueryParam.getBrandId() != null) {
            wrapper.eq("brand_id",productQueryParam.getBrandId());
        }
        if (productQueryParam.getProductCategoryId() != null) {
            wrapper.eq("product_category_id",productQueryParam.getProductCategoryId());
        }
        wrapper.orderByDesc("id");
        
        Page<PmsProduct> pages = productMapper.selectPage(page, wrapper);
        List<PmsProduct> list = pages.getRecords();
        long total = pages.getTotal();
        return pages;
    }

    
    /**
     * 批量修改审核状态
     * 这里的添加的记录表是不会将重复的元素去除的
     * @param ids
     * @param verifyStatus
     * @param detail
     * @return
     */
    @Override
    public int updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
        PmsProduct product = new PmsProduct();
        product.setVerifyStatus(verifyStatus);
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        ArrayList<PmsProductVertifyRecord> list = new ArrayList<>();
        int count = productMapper.update(product, wrapper);
        //修改完审核状态后插入审核记录
        for (Long id : ids){
            PmsProductVertifyRecord record = new PmsProductVertifyRecord();
            record.setProductId(id);
            record.setCreateTime(new Date());
            record.setDetail(detail);
            record.setStatus(verifyStatus);
            record.setVertifyMan("test");
            list.add(record);
        }
        productVertifyRecordDao.insertList(list);
        return count;

    }

    /**
     * 批量修改商品上架状态
     * @param ids
     * @param publishStatus
     * @return
     */
    @Override
    public int updatePublishStatus(List<Long> ids, Integer publishStatus) {
        PmsProduct record = new PmsProduct();
        record.setPublishStatus(publishStatus);
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        int result = productMapper.update(record, wrapper);
        return result;
    }


    /**
     * 批量修改商品推荐状态
     * @param ids
     * @param recommendStatus
     * @return
     */
    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        PmsProduct record = new PmsProduct();
        record.setRecommandStatus(recommendStatus);
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        int result = productMapper.update(record, wrapper);
        return result;
    }

    /**
     * 批量修改新品状态
     * @param ids
     * @param newStatus
     * @return
     */
    @Override
    public int updateNewStatus(List<Long> ids, Integer newStatus) {
        PmsProduct record = new PmsProduct();
        record.setNewStatus(newStatus);
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        int result = productMapper.update(record, wrapper);
        return result;
    }

    /**
     * 批量删除商品
     * @param ids
     * @param deleteStatus
     * @return
     */
    @Override
    public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
//        PmsProduct record = new PmsProduct();
//        record.setDeleteStatus(deleteStatus);
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
//        int result = productMapper.update(record, wrapper);
        int delete = productMapper.delete(wrapper);
        return delete;
    }

    /**
     * 根据商品名称或者货号模糊查询
     * @param keyword
     * @return
     */
    @Override
    public List<PmsProduct> list(String keyword) {
        QueryWrapper<PmsProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("delete_status",0);
        if(!StringUtils.isEmpty(keyword)){
            wrapper.like("name",keyword)
                    .or()
                    .like("product_sn",keyword);
        }
        List<PmsProduct> products = productMapper.selectList(wrapper);
        return products;
    }
}




